﻿using System;
using System.Net;
using System.IO;

namespace Utils
{
	public static class HttpWebRequest2
	{
		// The timeout is the amount of time allowed to connect AND the amount of time allowed to download the data so it can be twive the timeout value in the worst case (unlikely).
		public static HttpWebResponse SendGETRequest(string url, string agent, CookieContainer cookieContainer, TimeSpan timeout)
		{
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.UserAgent = agent;
			request.Method = "GET";
			request.ContentType = "text/html";
			request.CookieContainer = cookieContainer;
			request.Timeout = (int)timeout.TotalMilliseconds;
			request.ReadWriteTimeout = (int)timeout.TotalMilliseconds;

			return (HttpWebResponse)request.GetResponse();
		}

		// The timeout is the amount of time allowed to connect AND the amount of time allowed to download the data so it can be twive the timeout value in the worst case (unlikely).
		public static HttpWebResponse SendPOSTRequest(string textToSend, string url, string agent, CookieContainer cookieContainer, TimeSpan timeout)
		{
			byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes(textToSend);

			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.UserAgent = agent;
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = dataToSend.Length;
			request.CookieContainer = cookieContainer;
			request.Timeout = (int)timeout.TotalMilliseconds;
			request.ReadWriteTimeout = (int)timeout.TotalMilliseconds;

			using (Stream webStream = request.GetRequestStream())
			{
				webStream.Write(dataToSend, 0, dataToSend.Length);
			}

			return (HttpWebResponse) request.GetResponse();
		}
	}
}
